<?php

class LoginController extends Controller
{
	public $defaultAction = 'login';

	private $returnUrl="";
	
	private $registrationUrl="";

	/**
	 * Displays the login page
	 */
	public function actionLogin()
	{
		if (Yii::app()->user->isGuest) {
			$model=new UserLogin;
			// collect user input data
			if(isset($_POST['UserLogin']))
			{
				$model->attributes=$_POST['UserLogin'];
				// validate user input and redirect to previous page if valid
				if($model->validate()) {
					$this->lastViset();
					if (strpos(Yii::app()->user->returnUrl,'/index.php')!==false) {
						$this->redirect(Yii::app()->controller->module->returnUrl);
					}
					else {
						$this->redirect(Yii::app()->user->returnUrl);
					}
				}
			}
			// display the login form
			$this->render('/user/login',array('model'=>$model,"urlRegistration"=>Yii::app()->getModule('user')->registrationUrl));
		} else
		$this->redirect(Yii::app()->controller->module->returnUrl);
	}

	/**
	 * Displays the login page
	 */
	public function actionLoginDepuisPanier()
	{
		if (Yii::app()->user->isGuest) {
			$model=new UserLogin;
			// collect user input data
			if(isset($_POST['UserLogin']))
			{
				$model->attributes=$_POST['UserLogin'];
				// validate user input and redirect to previous page if valid
				if($model->validate()) {
					$this->lastViset();
					$client = Client::getClientFromUser();
					if($client != null && isset($client)) {
						$this->redirect($this->createUrl("/client/update",array("id"=>$client->id)));
					}
					else {
						$this->redirect($this->createUrl("/client/create"));
					}
				}
			}
			// display the login form
			$this->render('/user/login',array('model'=>$model,"urlRegistration"=>$this->createUrl("/user/registration/registrationDepuisPanier")));
		} else
		$this->redirect(Yii::app()->controller->module->returnUrl);
	}

	private function lastViset() {
		$lastVisit = User::model()->notsafe()->findByPk(Yii::app()->user->id);
		$lastVisit->lastvisit = time();
		$lastVisit->save();
	}
}